import cn from 'classnames';
import React, { useState, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Line } from 'rc-progress';
import Upload from 'rc-upload';
import fetch from 'API/fetch';
import FormData from 'form-data';
import { withRouter } from 'react-router';
import { CheckmarkOutline32 as Success9 } from '@carbon/icons-react';
import notification from '@kuiper-components/notification';
import Button from '@kuiper-components/button';
import s from './style.module.css';

const Step2Html = ({ text, percent }) => {
	return (
		<div>
			<p className={cn(s.tac, s.percent)}>{percent}%</p>
			<Line percent={percent} strokeWidth="2" strokeColor="#0b6df6" />
			<p className={s.tac}>资产正在{text}，请稍等...</p>
		</div>
	);
};
Step2Html.propTypes = {
	text: PropTypes.string.isRequired,
	percent: PropTypes.number,
};

const Step3Html = ({ total, success, error, data }) => {
	return (
		<div>
			<p>
				<span>总计：{total}</span>
				<span className={s.ml20}>成功：{success}</span>
				<span className={s.ml20}>失败：{error}</span>
			</p>
			{error > 0 && (
				<>
					<p className={s.tit}>添加失败资产如下：</p>
					<div>
						<div className={s.tabletit}>
							<span>资产名称</span>
							<span>资产地址</span>
							<span>失败原因</span>
						</div>
						<ul className={s.errortable}>
							{data.length &&
								data.map((item, index) => (
									<li key={index}>
										<span>{item.name}</span>
										<span>{item.address}</span>
										<span>{item.source}</span>
									</li>
								))}
						</ul>
					</div>
				</>
			)}
			{error === 0 && (
				<div className={s.icons}>
					<Success9 className={s.success} />
					<p>全部添加成功</p>
				</div>
			)}
		</div>
	);
};
Step3Html.propTypes = {
	total: PropTypes.number,
	success: PropTypes.number,
	error: PropTypes.number,
	data: PropTypes.array,
};
let out = true;

function Batch({
	match: {
		params: { assetType },
	},
}) {
	const [step, setStep] = useState(1);
	const [progress, setProgress] = useState(0);
	const [dataNum, setDataNum] = useState({ total: 0, success: 0, error: -1 });
	const [tdata, setTdata] = useState([]);
	// 封装整体步骤的方法
	function getStatus() {
		fetch('/api/v2/jobs/batch_status?asset_type=host', {
			method: 'GET',
		}).then(res => {
			if (!res.type) {
				changeTab(1);
			} else {
				if (res.progress === 100) {
					const len = res.assets.length;
					let successLen = 0;
					const data = [];
					res.assets.forEach(item => {
						if (item.status === '成功') {
							successLen += 1;
						} else {
							data.push({
								name: item.name,
								address: item.target,
								source: item.detail,
							});
						}
					});
					setDataNum(x => ({
						total: len,
						success: successLen,
						error: len - successLen,
					}));
					setTdata(x => (x = data));
					changeTab(3);
				} else {
					setProgress(x => (x = res.progress));
					changeTab(2);
					getStatus();
				}
			}
		});
	}
	// 获取数据
	useEffect(() => {
		getStatus();
		return () => {
			out = false;
		};
	}, []);
	const customReq = obj => {
		const formData = new FormData();
		formData.append('file', obj.file);
		formData.append('asset_type', 'host');
		fetch('/api/v2/jobs/batch_import', {
			method: 'POST',
			body: formData,
		})
			.then(res => {
				if (res.code === 200) {
					getStatus();
				}
			})
			.catch(e => {
				notification.error({
					message: e.message,
					placement: 'top',
				});
				setTimeout(() => {
					changeTab(1);
				}, 5000);
			});
	};
	// 三栏切换
	function changeTab(n) {
		setStep(n);
	}
	// 继续添加
	const add = () => {
		changeTab(1);
		setProgress(x => (x = 0));
		setDataNum(x => ({
			total: 0,
			success: 0,
			error: -1,
		}));
		fetch('/api/v2/jobs/batch_status?clean=1&asset_type=host', {
			method: 'get',
		}).then(res => {});
	};
	// 文件大小校验
	const beforeUpload = f => {
		return new Promise((resolve, reject) => {
			if (f.size > 2 * 1024 * 1024) {
				notification.error({
					message: '文件大小超出限制',
					placement: 'top',
				});
				reject(new Error('文件大小超出限制'));
			}
			resolve(f);
		});
	};
	return (
		<div className={s.body}>
			<div className={cn(s.content)}>
				<div className={s.allstep}>
					<div className={cn(s.step, step !== 1 ? s.grey : false)}>
						{step !== 1 && <Success9 className={cn(s.iconsize, s.vam)} />}
						选择文件
						<span className={s.single}></span>
					</div>
					<div className={cn(s.step, s.ml10, step !== 2 ? s.grey : false)}>
						{step === 3 && <Success9 className={cn(s.iconsize, s.vam)} />}
						<span>批量添加</span>
						<span className={s.front}></span>
						<span className={s.single}></span>
					</div>
					<div className={cn(s.step, s.ml10, step !== 3 ? s.grey : false)}>
						添加结果
						<span className={s.front}></span>
					</div>
				</div>
				<div className={step === 1 ? s.info : step === 2 ? s.info : s.ins}>
					{step === 1 && (
						<div>
							<p>1.上传文件格式支持xls和xlsx，大小不超过2MB。</p>
							<p>2.每次最多可以添加500条记录。</p>
						</div>
					)}
					{step === 2 && <Step2Html text={'添加'} percent={progress} />}
					{step === 3 && (
						<Step3Html
							total={dataNum.total}
							success={dataNum.success}
							error={dataNum.error}
							data={tdata}
						/>
					)}
				</div>
				{step === 1 && (
					<div className={s.btns}>
						<Button
							className={s.def}
							onClick={() =>
								(window.location.href =
									'/api/v2/files/host_assets_template.xlsx')
							}
						>
							下载模版
						</Button>
						<Upload
							className={cn(s.ml20, s.upload)}
							accept={'.xlsx,.xls'}
							customRequest={customReq}
							beforeUpload={beforeUpload}
						>
							选择文件
						</Upload>
					</div>
				)}
				{step === 3 && (
					<div className={s.btns}>
						<Button className={s.def} onClick={add}>
							继续添加
						</Button>
						<Link to={'/asset-manage/manage/host'}>
							<Button primary className={s.ml20}>
								返回资产列表
							</Button>
						</Link>
					</div>
				)}
			</div>
		</div>
	);
}
Batch.propTypes = {
	className: PropTypes.string,
	history: PropTypes.shape({
		push: PropTypes.func.isRequired,
		replace: PropTypes.func.isRequired,
	}).isRequired,
	location: PropTypes.shape({
		search: PropTypes.string.isRequired,
	}).isRequired,
	match: PropTypes.shape({
		params: PropTypes.shape({
			assetType: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
};
export default withRouter(Batch);
